<!-- Author: Deepak Teckchandani - 2012-2013 -->
<!-- <!DOCTYPE html> -->
<!-- <html lang="en"> -->
<title>UML Sequence Diagram Tool</title>
<script>
// global variables
var json;
//var flag = 0; // 0 = MOVE and 1 = RESIZE
var R; // raphael papaer object
var downloadState;
var currentState = -1; // for undo/redo

// flags
var dotted = false;
var alt = false;
var opt = false;
var loop = false;

// constants
var rw = 10; 
var rh =  30;
var rox = 100;
var roy = 100;
var drx = 250;
var dx = 10;
var dy = 30; //var my = roy + dy; ## real value, remove below if neeeded
var my = roy;

// global arrays to hold objects data
var map = new Array();     // stores all sequence diagram objects
var idList = new Array();  // stores list of unique ID's used
var history = new Array(); // stores history of diagrams
var optList = new Array(); // stores the Opt objects
var loopList = new Array();// stores the Loo[ objects
var altList = new Array(); // stores the Alt objects
</script>		
	
<script src="<?php echo base_url('/javascript/raphael.js');?>"></script>
<script src="<?php echo base_url('/javascript/jquery.js');?>"></script>		
<script src="<?php echo base_url('/javascript/raphaeljs.serialize.js');?>"></script>
<script src="<?php echo base_url('/javascript/raphael.export.js');?>"></script>
<script src="<?php echo base_url('/javascript/json2.js');?>"></script>
<script src="<?php echo base_url('/javascript/raphael.json.js');?>"></script>
<script src="<?php echo base_url('/javascript/jsonify.js');?>"></script>
<script src="<?php echo base_url('/javascript/utilities.js');?>"></script>
		
<script>	
window.onload = function () {
 R = Raphael("diagram");
};

function exists(list,x)
{
 for(i in list)
	{
	 if(list[i].text.attr("text") == x){return true;}
	}
 return false;	
}			

function find(list,x)
{
 for(i in list)
	{
	 if(list[i].text.attr("text") == x){return list[i];}
	}
 return false;	
}

function setDotted()
{dotted = true;}

function UnsetDotted()
{dotted = false;}

function setOpt()
{opt = true;}

function UnsetOpt()
{
 opt = false;
 var x = document.getElementById("option3");
 x.style.backgroundColor="";
 my = my + dy*2;
 hide('endopt');
}

function setAlt()
{alt = true;}

function UnsetAlt()
{
 alt = false;
 var x = document.getElementById("option4");
 x.style.backgroundColor="";
 my = my + dy*2;
 hide('endalt');			 
 hide('elsealt');
 hide('ifalt');				 
}

function setLoop()
{loop = true;}

function UnsetLoop()
{
 loop = false;
 var x = document.getElementById("option5");
 x.style.backgroundColor="";
 my = my + dy*2;
 hide('endloop');			 
}
		
function hoverStart() 
{
 // if (Raphael.type != 'VML') {    // Work-around loss of event handling on toFront().
			// background.toFront();
			// foreground.toFront();
		 // }
 this.animate({opacity: 0.5, fill:"pink"}, 200);
}
	
function hoverEnd() 
{this.animate({opacity: 1, fill:"white"}, 200);}

function dbclicker()
{
 for(j in map)
	{
	 if(map[j].ID == this.ID)
		{
		 loadData(map[j]);
		 return;
		}
	}
	return false;	
}
		
function clearOptions(e)
{
 var x=document.getElementById(e);
 for(i in x)
	{
	 x.remove(i);
	}
}
		
function loadData(object)
{
 hide("form1");
 show("editForm1");
 document.forms["editForm1"]["id"].value = object.ID;
 document.forms["editForm1"]["object1"].value = object.text.attr("text");
 clearOptions("messages");
 clearOptions("objectoptions");
 
 
// fill in the object list options
 populateObjOptions(object);
 populateMsgOptions(object);
}

function populateObjOptions(object)
{
 for(i in map)
	{
	 var opt = document.createElement("option");
	 opt.text = map[i].text.attr("text");
	 opt.value = i;
	 document.forms["editForm1"]["objectoptions"].options.add(opt);
	}
}

function populateMsgOptions(object)
{
 for(i in object.msgList)
	{
	 var opt = document.createElement("option");
	 opt.text = object.msgList[i].text.attr("text");
	 opt.value = i;
	 document.forms["editForm1"]["messages"].options.add(opt);
	}
}

function loadMessageOptions(e)
{
 clearOptions("messageoptions");
 var objIndex = document.getElementById(e).selectedIndex;
 var objName = document.getElementById(e).options[objIndex].text;
 var object = find(map,objName);
 for(i in object.msgList)
	{
	 var opt = document.createElement("option");
	 opt.text = object.msgList[i].text.attr("text");
	 opt.value = i;
	 document.forms["editForm1"]["messageoptions"].options.add(opt);
	}
}
		
function submitChange(action) // "name"||"message"||"delete"||"add"
{
 var id = document.forms["editForm1"]["id"].value;
 var name = document.forms["editForm1"]["object1"].value;
 for(j in map)
	{
	 if(map[j].ID == id)
		{
		 var object = map[j];
		 break;
		}
	}
 
 // change message name
 var messageIndex = document.getElementById("messages").selectedIndex;
 var newMessage = document.forms["editForm1"]["method"].value;
 if(messageIndex != -1){object.msgList[messageIndex].text.attr({text:newMessage});}

 //Change object name
 object.text.attr({text:name});
 
 if(action == "insert")
   {
   var objIndex = document.getElementById("objectoptions").selectedIndex;
   var objName = document.forms["editForm1"]["object2"].value;

   var object2 = find(map,objName);
   alert(objName);
   
   var messageIndex1 = document.getElementById("messageoptions").selectedIndex;
 
   var thresholdY = object2.msgList[messageIndex1].attr("path")[0][2];
	
   var insertMessage = document.forms["editForm1"]["methodinsert"].value;
   alert(insertMessage);
   
   oldMy = my;
   my = thresholdY; // Use this value as "my" for this operation			   
   
   
  var k = 1;
  var A = object;
  var B = object2;
  var sizeA = A.objList.length;
  var sizeB = B.objList.length;
  

  var xA = A.objList[sizeA-1].attr("x");
  var yA = A.objList[sizeA-1].attr("y"); 

  var xB = B.objList[sizeB-1].attr("x");
  var yB = B.objList[sizeB-1].attr("y");
   
  
   var x1 = xA;  
   var x2 = xB;  
   if(x1<=x2){x1 = x1 + dx;}
   else{x2 = x2 + dx;k = -1;}
	  
	  
   var h1 = my-yA+dy; 
   var h2 = my-yB+dy; 

  
  var data = [["M", x1, my], ["L", x2, my]];
  if(x1 > x2){data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2+10, my-5],["M", x2, my], ["L", x2+10, my+5]];}
  else { data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2-10, my-5],["M", x2, my], ["L", x2-10, my+5]];}

  if(A.text.attr('text') == B.text.attr('text'))
	{data =[["M", x1, my+10], ["L", x1+30, my+10], ["L", x1+30, my-10], ["L", x1, my-10],["M",x1, my-10], ["L", x1+10, my-15],["M",x1, my-10], ["L", x1+10, my-5] ];}
  
  if(dotted){ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black", "stroke-dasharray": "- " });}
  else{ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black"});}
  message.text = R.text(x1+250/2*k, my-10, insertMessage).attr({fill:'blue', 'font-size':12,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});
  
  A.msgList.splice(messageIndex,0,message); // add to array
 			  
	  
	  
	  
	  
	  // find right mini object
	  var A1 = findBox(A,my);
	  var B1 = findBox(B,my);
	  
	  A1.attr({height:A1.attr("height")+dy}); 
	  
	  data = A.timeline.attr("path");
	  data[1][2] = my+dy*2;
	  A.timeline.attr({path: data});				  
	  
	  B1.attr({height:B1.attr("height")+dy});   
	  data = B.timeline.attr("path");
	  data[1][2] = my+dy*2;
	  B.timeline.attr({path: data});
	  
	  for(i in map)
		 {
		  for(k in map[i].objList)
			 {
			  // Move box
			  if((map[i].objList[k]==A1) || (map[i].objList[k]==B1)){continue;}
			  if(map[i].objList[k].attr("y") >= thresholdY) 
				{
				 map[i].objList[k].attr({y:map[i].objList[k].attr("y")+dy});
				}
			  // Resize box
			  else if((map[i].objList[k].attr("y") < thresholdY) && (map[i].objList[k].attr("y")+map[i].objList[k].attr("height"))>thresholdY)
				{
				 map[i].objList[k].attr({height:map[i].objList[k].attr("height")+dy});
				}							
			 }
		  
		  for(j in map[i].msgList)
			 {  
			  if(map[i].msgList[j].attr("path")[0][2] >= thresholdY)
				{
				 if(map[i].msgList[j] == message){continue;} // In order to not shift newly inserted message
				 data = map[i].msgList[j].attr("path");
				 data[0][2] = data[0][2] + dy;
				 data[1][2] = data[1][2] + dy;
				 data[2][2] = data[2][2] + dy;
				 data[3][2] = data[3][2] + dy;
				 data[4][2] = data[4][2] + dy;
				 data[5][2] = data[5][2] + dy;
				 map[i].msgList[j].attr({path:data});
				 map[i].msgList[j].text.attr({y:map[i].msgList[j].text.attr("y")+dy});
				}
			 }
		 }
	  
	  
	  // Set my to its previous value;
	  my = oldMy;
   }
	 
 //Delete message
 else if(action == "delete")
   {
	var thresholdY = object.msgList[messageIndex].attr("path")[0][2];
	object.msgList.splice(messageIndex,1); // delete from array
	var A1 = findBox(object,thresholdY+dy);
	if(A1.attr("height") <= rh)
	  {
	   
	   var index = object.objList.indexOf(A1); 
	   object.objList.splice(index,1);
	  }
		
	
	for(i in map)
		{
		 for(k in map[i].objList)
			{	 
			 //if((map[i].objList[k]==A1) || (map[i].objList[k]==B1)){continue;}
			 // Delete unreferenced destination box
			 if((map[i].objList[k].attr("y")==thresholdY) && (map[i].objList[k].attr("height") <= rh))
				{
				 map[i].objList.splice(k,1);
				 continue;
				}
			   // Move box	
			 if(map[i].objList[k].attr("y") >= thresholdY) 
				{
				 map[i].objList[k].attr({y:map[i].objList[k].attr("y")-dy});
				}
			  // Resize box
			 else if((map[i].objList[k].attr("y") < thresholdY) && (map[i].objList[k].attr("y")+map[i].objList[k].attr("height"))>thresholdY)
				{
				 
				 map[i].objList[k].attr({height:map[i].objList[k].attr("height")-dy});
				}							
			}
		  
		 for(j in map[i].msgList)
			{  
			 if(map[i].msgList[j].attr("path")[0][2] >= thresholdY)
				{
				 //if(map[i].msgList[j] == message){continue;} // In order to not shift newly inserted message
				 data = map[i].msgList[j].attr("path");
				 data[0][2] = data[0][2] - dy;
				 data[1][2] = data[1][2] - dy;
				 data[2][2] = data[2][2] - dy;
				 data[3][2] = data[3][2] - dy;
				 data[4][2] = data[4][2] - dy;
				 data[5][2] = data[5][2] - dy;
				 map[i].msgList[j].attr({path:data});
				 map[i].msgList[j].text.attr({y:map[i].msgList[j].text.attr("y")-dy});
				}
			}
		}			
	 my = my - dy; // Take "my" back one step to account for deletion
   }
 
 
 hide("editForm1");
 globalUpdate();			 
 currentState++;			 
 history[currentState] = objToJson(map,optList,loopList,altList);
 history = history.slice(0,currentState+1);
		 
 R.clear();
 alert("clear");
 jsonToObj(history[currentState]);
}
		
function findBox(A,y)
{
 y1 = y-dy;
 for(i in A.objList)
	{
	 if( (A.objList[i].attr("y") <= y1) && ( y1 <= (A.objList[i].attr("y")+A.objList[i].attr("height"))))
	   {
		return A.objList[i];
	   }
	}
 return false;	
}
		
function globalUpdate()
{
 for(i in map)
	{
	 var data = map[i].timeline.attr("path");
	 data[1][2] = my+dy*2;
	 map[i].timeline.attr({path:data});
	}
}

function idGen()
{
 while(true)
  {
   var x = Math.floor((Math.random()*100)+1);
   var t = idList.indexOf(x);
   if(t==-1)
	 {
	  idList.push(x);
	  return x;
	 }
  } 
}			
		
function submitForm0()
{
 var objName1 = document.forms["form0"]["object1"].value;
 
 var id1 = idGen(); 
 var text1 = R.text(rox, roy-dy, objName1).attr({fill:'blue', 'font-size':15,"font":"Arial", 'stroke-width':2 ,'text-anchor':'middle'});				  
 var data = [["M", rox+rw/2, roy-5], ["L", rox+rw/2, my+dy*2]];
 var timeline1 = R.path(data).attr({ "stroke-width": 1, stroke: "black", 'arrow-end': 'classic', "stroke-dasharray": "- " });				  			  
 rox = rox + drx; // Make space for the new box to be drawn.
 
 var A = new Entity(text1, "");
 A.timeline = timeline1;
 A.ID = id1;
 map.push(A);
 
 R.setSize(rox+dx*10, my+dy*4);
 currentState++;			 
 history[currentState] = objToJson(map,optList,loopList,altList);
 history = history.slice(0,currentState+1);  
 hide("form0");
}

function drawType1(objName1,methodName,objName2,checkbx1,checkbx2,k)
{
  var A = find(map,objName1);
  var sizeA = A.objList.length;
  var id2 = idGen();	
  var text2 = R.text(rox, roy-dy, objName2).attr({fill:'blue', 'font-size':15,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});				  
  var data1 = [["M", rox+rw/2, roy-5], ["L", rox+rw/2, my+dy*2]];
  var timeline2 = R.path(data1).attr({ "stroke-width": 1, stroke: "black", 'arrow-end': 'classic', "stroke-dasharray": "- " });
  var object2 = R.rect(rox, my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});	
  object2.ID = id2;				  
  object2.hover(hoverStart, hoverEnd);
  object2.dblclick(dbclicker);		
  rox = rox + drx; // Make space for the new box to be drawn.
  
  var x1 = A.objList[sizeA-1].attr("x");
  var x2 = object2.attr("x");
  if(x1<=x2){x1 = x1 + dx;}
  else{x2 = x2 + dx;k = -1;}
  
  var h1 = my-A.objList[sizeA-1].attr("y")+dy;
  if(checkbx1)
	{
	 my = my + dy; 					
	 object1 = R.rect(A.objList[sizeA-1].attr("x"), my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
	 object1.ID = A.ID;				  
	 object1.hover(hoverStart, hoverEnd);
	 object1.dblclick(dbclicker);							 
	 A.objList.push(object1);
	 h1 = rh;
	}
  
  var data = [["M", x1, my], ["L", x2, my]];
  data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2-10, my-5],["M", x2, my], ["L", x2-10, my+5]];
  if(dotted){ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black" ,"stroke-dasharray": "-" });}
  else{ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black"});}		  
  message.text = R.text(x1+250/2*k, my-10, methodName).attr({fill:'blue', 'font-size':12,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});
  A.msgList.push(message);
  my = my + dy;
   
  var B = new Entity(text2, object2);
  B.timeline = timeline2;
  B.ID = id2;
  map.push(B);
  
  sizeA = A.objList.length;
  var A1 = A.objList[sizeA-1];
  A1.attr({height:h1});

}
function drawType2(objName1,methodName,objName2,checkbx1,checkbx2,k)
{
  var A = find(map,objName1);
  var B = find(map,objName2);
  var sizeA = A.objList.length;
  var sizeB = B.objList.length;
  
  if(sizeA>0) 
	{
	 var xA = A.objList[sizeA-1].attr("x");
	 var yA = A.objList[sizeA-1].attr("y");
	} 
	else
	{
	 var xA = A.text.attr('x');
	 var yA = A.text.attr('y');
	 checkbx1 = true;
	}
  
 if(sizeB>0) 
	{
	 var xB = B.objList[sizeB-1].attr("x");
	 var yB = B.objList[sizeB-1].attr("y");
	} 
	else
	{
	 var xB = B.text.attr('x');
	 var yB = B.text.attr('y');
	 checkbx2 = true;
	}
 // if(sizeB>0) {var xA = A.objList[sizeA-1].attr("x");} else{var xA = A.text.attr('x');}	  
	var x1 = xA;  
	var x2 = xB;  
	if(x1<=x2){x1 = x1 + dx;}
	else{x2 = x2 + dx;k = -1;} 
	var h1 = my-yA+dy; 
	var h2 = my-yB+dy; 
  if((checkbx1 || checkbx2) && sizeA>0) {my = my + dy;}
  if(checkbx1)
	{	
	 object1 = R.rect(xA, my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
	 object1.ID = A.ID;				  
	 object1.hover(hoverStart, hoverEnd);
	 object1.dblclick(dbclicker);							 
	 A.objList.push(object1);
	 h1 = rh;
	 my = my + dy;
	 h2 = my - yB;
	}
  if(checkbx2)
	{	
	 object2 = R.rect(xB, my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
	 object2.ID = B.ID;				  
	 object2.hover(hoverStart, hoverEnd);
	 object2.dblclick(dbclicker);						 
	 B.objList.push(object2);
	 h2 = rh;
	} 					

  var data = [["M", x1, my], ["L", x2, my]];
  if(x1 > x2){data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2+10, my-5],["M", x2, my], ["L", x2+10, my+5]];}
  else { data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2-10, my-5],["M", x2, my], ["L", x2-10, my+5]];}

  if(A.text.attr('text') == B.text.attr('text'))
	{
	 data =[["M", x1, my+10], ["L", x1+30, my+10], ["L", x1+30, my-10], ["L", x1, my-10],["M",x1, my-10], ["L", x1+10, my-15],["M",x1, my-10], ["L", x1+10, my-5] ];
	}
  
  if(dotted){ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black", "stroke-dasharray": "-" });}
  else{ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black"});}
  message.text = R.text(x1+250/2*k, my-10, methodName).attr({fill:'blue', 'font-size':12,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});
  A.msgList.push(message);
  my = my + dy;				  

  sizeA = A.objList.length;
  sizeB = B.objList.length;
  var A1 = A.objList[sizeA-1];
  var B1 = B.objList[sizeB-1];
  A1.attr({height:h1});
  data = A.timeline.attr("path");
  data[1][2] = my+dy*2;
  A.timeline.attr({path: data});				  
  
  B1.attr({height:h2});
  data = B.timeline.attr("path");
  data[1][2] = my+dy*2;
  B.timeline.attr({path: data});
}
function drawType3(objName1,methodName,objName2,checkbx1,checkbx2,k)
{
  var id1 = idGen(); 
  var id2 = idGen(); 
  var text1 = R.text(rox, roy-dy, objName1).attr({fill:'blue', 'font-size':15,"font":"Arial", 'stroke-width':2 ,'text-anchor':'middle'});				  
  var data = [["M", rox+rw/2, roy-5], ["L", rox+rw/2, my+dy*2]];
  var timeline1 = R.path(data).attr({ "stroke-width": 1, stroke: "black", 'arrow-end': 'classic', "stroke-dasharray": "- " });				  
  var object1 = R.rect(rox, my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
  object1.ID = id1;				  
  object1.hover(hoverStart, hoverEnd);
  object1.dblclick(dbclicker);				  
  rox = rox + drx; // Make space for the new box to be drawn.

  my = my+dy;

  var text2 = R.text(rox,roy-dy, objName2).attr({fill:'blue', 'font-size':15,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});
  data = [["M", rox+rw/2, roy-5], ["L", rox+rw/2, my+dy*2]];
  var timeline2 = R.path(data).attr({ "stroke-width": 1, stroke: "black", 'arrow-end': 'classic', "stroke-dasharray": "- " });	
  var object2 = R.rect(rox, my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
  object2.ID = id2;
  object2.hover(hoverStart, hoverEnd);
  object2.dblclick(dbclicker);					  
  rox = rox + drx; // Make space for the new box to be drawn.
  
  var x1 = object1.attr("x");
  var x2 = object2.attr("x");
  if(x1<=x2){x1 = x1 + dx;}
  else{x2 = x2 + dx;k = -1;}
  
  data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2-10, my-5],["M", x2, my], ["L", x2-10, my+5]];
  if(objName1 == objName2 )
	{
	 data =[["M", x1, my+10], ["L", x1+30, my+10], ["L", x1+30, my-10], ["L", x1, my-10],["M",x1, my-10], ["L", x1+10, my-15],["M",x1, my-10], ["L", x1+10, my-5] ];
	}  
  if(dotted)
	{ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black", "stroke-dasharray": "-" });}
  else{ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black"});}
  message.text = R.text((x1+250/2*k), my-10, methodName).attr({fill:'blue', 'font-size':12,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});
  my = my + dy;   
  var A = new Entity(text1, object1);
  var B = new Entity(text2, object2);
  A.ID = id1;
  A.timeline = timeline1;
  B.timeline = timeline2;
  B.ID = id2;
  A.msgList.push(message);
  map.push(A);
  map.push(B);
}

function submitForm1()
{
 var objName1 = document.forms["form1"]["object1"].value;
 var methodName = document.forms["form1"]["method"].value;
 var objName2 = document.forms["form1"]["object2"].value;
 var checkbx1 = document.forms["form1"]["checkbox1"].checked;
 var checkbx2 = document.forms["form1"]["checkbox2"].checked;
 var k = 1;; // constant to multitply text element result by for text positioning
 if(!exists(map,objName1) && exists(map,objName2))
	{alert("Not allowed, build left to right");}             

 else if(exists(map,objName1) && !exists(map,objName2))
	{  drawType1(objName1,methodName,objName2,checkbx1,checkbx2,k);}  


else if(exists(map,objName1) && exists(map,objName2))
	{ drawType2(objName1,methodName,objName2,checkbx1,checkbx2,k);}

else if(!exists(map,objName1) && !exists(map,objName2))
	{ drawType3(objName1,methodName,objName2,checkbx1,checkbx2,k);}  
	
if(opt)
 {
 var currentConditionBox = optList[optList.length-1].nameBoundry; 
 var boxHeight = my - currentConditionBox.rect.attr('y');
 currentConditionBox.rect.attr({height:boxHeight});
 show("endopt");
 }
 else if(loop)
 {
 var currentConditionBox = loopList[loopList.length-1].nameBoundry; 
 var boxHeight = my - currentConditionBox.rect.attr('y');
 currentConditionBox.rect.attr({height:boxHeight});
 show("endloop");
 }
 if(alt)
 {
 var currentConditionBox = altList[altList.length-1].nameBoundry;
 var boxHeight = my - currentConditionBox.rect.attr('y');
 currentConditionBox.rect.attr({height:boxHeight});
 show("ifalt");
 show("elsealt");
 show("endalt");
 }
 globalUpdate();	
 R.setSize(rox+dx*10, my+dy*4);
 currentState++;			 
 history[currentState] = objToJson(map,optList,loopList,altList);
 history = history.slice(0,currentState+1);
 hide("form1");
}
		
function submitForm2()
{
 setOpt();
 drawConditionBox("OPT","form2","option3");
}

function submitForm3()
{
 setAlt();
 drawConditionBox("ALT","form3","option4");
}

function submitForm4()
{
 setLoop();
 drawConditionBox("LOOP","form4","option5");
}

function drawConditionBox(type,form,option)
{
 my = my + dy;
 var condition = document.forms[form]["condition"].value;
 var nameBoundry = R.rect(15, my, 45,20).attr({fill: "white", stroke: "black", opacity: "none"});
 nameBoundry.rect = R.rect(15, my, rox-drx+50, rh+10).attr({fill: "none", stroke: "black",'stroke-width':3,opacity: "none"});
 nameBoundry.name = R.text(35,my+10,type).attr({fill:'black', 'font-size':14,"font":"Arial", 'stroke-width':3 ,'text-anchor':'middle'});
 nameBoundry.text = R.text(65,my+30,"["+condition+"]").attr({fill:'black', 'font-size':14,"font":"Arial", 'stroke-width':3 ,'text-anchor':'middle'});			 
 if(type=="OPT"){ optList.push(new OptionObj(nameBoundry));}
 else if(type=="ALT"){ altList.push(new AltObj(nameBoundry));}
 else if(type=="LOOP"){ loopList.push(new LoopObj(nameBoundry));} 
 my = my + dy;
 var x = document.getElementById(option);
 x.style.backgroundColor="blue";	
 hide(form);
}
		
function toggleColor(color,notColor)
{ 
 var x = document.getElementById(color);
 x.style.backgroundColor="blue";	
 x = document.getElementById(notColor);
 x.style.backgroundColor="";	 
}

function Entity(text, object)
{
 this.text = text;
 this.objList = new Array();
 if(object != "") {this.objList.push(object);}
 this.msgList = new Array();
}

function OptionObj(nameBoundry)
{ this.nameBoundry = nameBoundry;}

function AltObj(nameBoundry)
{ this.nameBoundry = nameBoundry;}

function LoopObj(nameBoundry)
{ this.nameBoundry = nameBoundry;}

function putLineSeparationConditionBox()
{
 var obj = altList[altList.length-1].nameBoundry;
 data = [["M", obj.rect.attr("x"), my], ["L", obj.rect.attr("x")+obj.rect.attr("width"), my]];
 obj.line = R.path(data).attr({ "stroke-width": 2, stroke: "black"});
 var boxHeight = obj.rect.attr('height') + dy;
 obj.rect.attr({height:boxHeight});
 my = my + dy*2;			 
}
					
function exportServerSide()
{
 var str =  new Array();
 var temp = R.toSVG();
 var filename = "default";
 if(document.getElementById("diagramname").value){filename = document.getElementById("diagramname").value;}
 str[0] = filename;
 str[1] = temp;
 str = JSON.stringify(str);
 if (str=="")
   {
	alert("Empty String!");
	return;
   } 
 if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
	xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.onreadystatechange=function()
   {
	var remover;
	var flag = false;
	if ((xmlhttp.readyState==1))
	 { 
	  var x = document.getElementById("export");
	  x.style.backgroundColor="blue";
	  flag=true;
	 }
	 
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	  {
	   downloadState = true;
	   var x = document.getElementById("export");
	   x.style.backgroundColor="";	
	   alert(xmlhttp.responseText);		 
	  }
   }
   
 xmlhttp.open("POST","<?php echo base_url('/ajax/svgToPng.php');?>",true);
 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlhttp.send("data="+str);
}
		
function saveDiagram(str1)
{
json = objToJson(map,optList,loopList,altList);
var str = new Array();
str[0] = document.getElementById("diagramname").value;
str[1] = json;
str[2] = "<?php echo $this->session->userdata('user_id'); ?>";
str = JSON.stringify(str);
if (str=="")
  {
  alert("Empty String!");
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
	 if(xmlhttp.responseText == 1)
	   {alert("Diagram saved Successfully");}		 
	}
  }
xmlhttp.open("POST","<?php echo base_url('/ajax/saveDiagram.php');?>",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+str);
}

function fetchDiagram(name,userId)
{
var str = new Array();
str[0] = name;
str[1] = userId;
var data = JSON.stringify(str);

if (str=="")
  {
  alert("Empty String!");
  //return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
	jsonToObj(xmlhttp.responseText);
	document.getElementById("diagramname").value = name;
	}
  }

xmlhttp.open("GET","<?php echo base_url('/ajax/updateDB.php');?>?q="+data,true);  
xmlhttp.send();
}

function login()
{
var str = new Array();
str[0] = document.forms["editForm1"]["email"].value;
str[1] = document.forms["editForm1"]["pass"].value;;
if (str=="")
  {
  alert("Empty String!");
  //return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
	alert("response");
	alert(xmlhttp.responseText);
	jsonToObj(xmlhttp.responseText);
	}
  }
xmlhttp.open("GET","<?php echo base_url('/ajax/login_ajax.php');?>?q="+str,true);
xmlhttp.send();
}

function saveToDB()
{ 
 <?php if(!$this->session->userdata('user_name')) : ?>
	alert('Log in to be able to save your Diagram');
	return;
 <?php endif; ?>	
 alert('save');
 json = objToJson(map,optList,loopList,altList);
 saveDiagram(json);
}

function fetchFromDB(name,userId)
{
 <?php if(!$this->session->userdata('user_name')) : ?>
	alert('Log in to be able to load your Diagram');
	return;
 <?php endif; ?>
 alert('Load Diagram: ' + name);		 
 fetchDiagram(name,userId);
}
		
function objToJson(list,optionList,looperList,alterList)
{
 var objects = new Array();
 for(i in list)
   {
    var rectList =  new Array();   
    var messages =  new Array();     
	
    var ID =  list[i].ID;
    var lifeline = list[i].timeline;
    var objList = list[i].objList;
	var text = list[i].text;
	var msgList = list[i].msgList;
	for(j in objList)
      {
	   rectList.push({
                    type:      objList[j].type,
	                attrs:     objList[j].attrs
				    });
      }
	
	for(k in msgList)
      {
	   messages.push({
                    path:     msgList[k].attrs,
	                text:     msgList[k].text.attrs
				    });
      }
	
	objects.push({
	            lifeline:  lifeline.attrs,  
				ID:        ID,
				text:      text.attrs,
				rects:     rectList,
				msgs:      messages
				});    
   }
   
 var options = new Array();  
 for(i in optionList)
   {
    options.push({
	            nameBoundry:   optionList[i].nameBoundry.attrs,
				rect:          optionList[i].nameBoundry.rect.attrs,
				name:          optionList[i].nameBoundry.name.attrs,
				text:          optionList[i].nameBoundry.text.attrs
				});   
   }
   
 var loops = new Array();   
 for(i in looperList)
   {
    loops.push({
				nameBoundry:   looperList[i].nameBoundry.attrs,
				rect:          looperList[i].nameBoundry.rect.attrs,
				name:          looperList[i].nameBoundry.name.attrs,
				text:          looperList[i].nameBoundry.text.attrs
				});   
   }

 var alts = new Array();   
 for(i in alterList)
   {
    alts.push({
				nameBoundry:   alterList[i].nameBoundry.attrs,
				rect:          alterList[i].nameBoundry.rect.attrs,
				name:          alterList[i].nameBoundry.name.attrs,
				text:          alterList[i].nameBoundry.text.attrs
				});
    if(typeof alterList[i].nameBoundry.line != 'undefined'){ alts.push({line: alterList[i].nameBoundry.line.attrs}); }				
   }    

   var result = new Array();
   result.push(objects);
   result.push(options);   
   result.push(loops);
   result.push(alts);
   result.push(my);
   result.push(rox);
   return JSON.stringify(result);
}

function jsonToObj(jsonFormat)
{
 json = JSON.parse(jsonFormat);
 var objJson = json[0];
 var optJson = json[1];
 var loopJson = json[2];
 var altJson = json[3];
 my = json[4];
 rox = json[5];
 
 R.clear();
 R.setSize(rox,my+50);
 var objects = new Array();
 
 map = [];
 optList = [];
 loopList = [];
 altList = [];
 
 for(i in objJson)
   {
	var lifeline = R['path']().attr(objJson[i].lifeline);
	var ID = objJson[i].ID;
	var text = R['text']().attr(objJson[i].text);
	
	var A = new Entity(text,"");
	A.timeline = lifeline;
	A.ID = ID;
	
	for(j in objJson[i].rects)
	   {
        var rect = R['rect']().attr(objJson[i].rects[j].attrs).dblclick(dbclicker).hover(hoverStart, hoverEnd);	   
	    rect.ID = ID;
		A.objList[j] = rect;
   	   }
	for(k in objJson[i].msgs)
	   {
        var msg = R['path']().attr(objJson[i].msgs[k].path);	   
	    msg.text = R['text']().attr(objJson[i].msgs[k].text);
		A.msgList.push(msg);
   	   }
	   
	map.push(A);
   }
 for(i in optJson)
   {
    var nameBoundry = R['rect']().attr(optJson[i].nameBoundry);
    nameBoundry.rect = R['rect']().attr(optJson[i].rect);
	nameBoundry.name = R['text']().attr(optJson[i].name);
	nameBoundry.text = R['text']().attr(optJson[i].text);
    optList.push(new OptionObj(nameBoundry));
   }
   
 for(i in loopJson)
   {
    var nameBoundry = R['rect']().attr(loopJson[i].nameBoundry);
    nameBoundry.rect = R['rect']().attr(loopJson[i].rect);
	nameBoundry.name = R['text']().attr(loopJson[i].name);
	nameBoundry.text = R['text']().attr(loopJson[i].text);
    optList.push(new LoopObj(nameBoundry));
   }
   
 for(i in altJson)
   {
    var nameBoundry = R['rect']().attr(altJson[i].nameBoundry);
    nameBoundry.rect = R['rect']().attr(altJson[i].rect);
	nameBoundry.name = R['text']().attr(altJson[i].name);
	nameBoundry.text = R['text']().attr(altJson[i].text);
	if(typeof altJson[i].line != 'undefined'){nameBoundry.line = R['path']().attr(altJson[i].line);}
    altList.push(new AltObj(nameBoundry));
   }  
}		
				
function undo()
{
 currentState--;
 if(currentState==-1)
   {currentState++;/*alert("Can't go furthur");*/return;}
 R.clear();
 jsonToObj(history[currentState]);

}        

function redo()
{
 currentState++;
 if(currentState==history.length)
   {currentState--;/*alert("Can't go furthur");*/return;}
 R.clear();
 jsonToObj(history[currentState]);
}  

function iterateObjects()
{
 for(i in map)
	{
	 alert(map[i]);
	}
}

function editMessage(m) 
{
 var messageIndex = document.getElementById(m).selectedIndex;
 var objName1 = document.forms["editForm1"]["method"].value = document.getElementById(m).options[messageIndex].text;		 
}

function disableAllBut(e)
{
 document.getElementById("option3").disabled = true;
 document.getElementById("option4").disabled = true;
 document.getElementById("option5").disabled = true;
}

function enableAllBut(e)
{
 document.getElementById("option3").disabled = false;
 document.getElementById("option4").disabled = false;
 document.getElementById("option5").disabled = false;
}

function hideAll()
{
 document.getElementById("form0").style.display = 'none';
 document.getElementById("form1").style.display = 'none';
 document.getElementById("form2").style.display = 'none';
 document.getElementById("form3").style.display = 'none';
 document.getElementById("form4").style.display = 'none';
 document.getElementById("editForm1").style.display = 'none';
}			

function hide(e)
{
 obj1 = document.getElementById(e); 
 obj1.style.display = 'none';
}

function show(e)
{
 obj1 = document.getElementById(e); 
 obj1.style.display = 'block';
}		
</script>
</head>

<body>
	
	<div id="toolbox" >
	<button id="initializeobject" type="button" onclick="UnsetDotted();hideAll();show('form0');"> 
	<img class="optionimage" src="<?php echo base_url('/images/initialize1.png');?>" ></button><br><br>
	<button id="option1" type="button" onclick="UnsetDotted();hideAll();show('form1')"> 
	<img class="optionimage" src="<?php echo base_url('/images/option1.png');?>" ></button><br><br>
	<button  id="option2" type="button" onclick="setDotted();hideAll();show('form1')"> 
	<img class="optionimage" src="<?php echo base_url('/images/option2.png');?>" ></button><br><br>
	<button id="option3" type="button" onclick="hideAll();show('form2')"> 
	<img class="optionimage" src="<?php echo base_url('/images/optionOpt.png');?>" ></button><br><br>
	<button  id="option4" type="button" onclick="hideAll();show('form3')"> 
	<img class="optionimage" src="<?php echo base_url('/images/optionAlt.png');?>" ></button><br><br>
	<button id="option5" type="button" onclick="hideAll();show('form4')"> 
	<img class="optionimage" src="<?php echo base_url('/images/optionLoop.png');?>" ></button><br><br>
	<input id="editbutton" class="optionimage" type="button" value="EDIT" onclick="loadObjectsSelect('editForm2');show('editForm2');" >
	</div>
	
	<div id="inputbox" >
	<h1 style="text-align:center">Input Box </h1>
	Diagram Name <input id="diagramname" type="text" name="user" size="13">
	
	<form class="inputform" id="form0" name="input"  method="post" >
	<br>A: <input id="object1" type="text" name="user" size="13">
	<input type="button" value="Done" onclick="submitForm0()" >
	</form>
	
	<form class="inputform" id="form1" name="input"  method="post" >
	<br>A: <input id="object1" type="text" name="user" size="13">
	<input id="checkbox1" type="checkbox" name="new" value="new">New<br><br>
	B: <input id="object2" type="text" name="user" size="13">
	<input id="checkbox2" type="checkbox" name="new" value="new">New<br><br>
	Method: <input id="method" type="text" name="user" size="13"><br><br>
	<input type="button" value="Done" onclick="submitForm1()" >
	</form>
	
	<form class="inputform" id="form2" name="input"  method="post"  >Opt
	<br>Condition: <input id="condition" type="text" name="user" size="13"><br><br>
	<input type="button" value="Done" onclick="submitForm2()" ><br>
	</form>
	<input class="hiddenbutton" id="endopt" type="button" value="end" onclick="UnsetOpt();enableAllBut('')" >
	
	<form class="inputform" id="form3" name="input"  method="post" >Alt
	<br>Condition: <input id="condition" type="text" name="user" size="13"><br><br>
	<input type="button" value="Done" onclick="submitForm3()" ><br>
	</form>
	<input class="hiddenbutton" id="endalt" type="button" value="end" onclick="UnsetAlt();enableAllBut('')"  >
	<input class="hiddenbutton" id="elsealt" type="button" value="else" onclick="toggleColor('elsealt','ifalt');putLineSeparationConditionBox()"   >
	<input class="hiddenbutton" id="ifalt" type="button" value="if"  >
	
	<form class="inputform" id="form4" name="input"  method="post"  >Loop
	<br>Condition: <input id="condition" type="text" name="user" size="13"><br><br>
	<input type="button" value="Done" onclick="submitForm4()" ><br>
	</form>
	<input class="hiddenbutton" id="endloop" type="button" value="end" onclick="UnsetLoop();enableAllBut('')"  >
	
	<form class="inputform" id="editForm1" name="input"  method="post" >
	<input id="id" type="text" name="user" size="13" style="display:none" >
	<br>A: <input id="object1" type="text" name="user" size="13"><br><br>
	<select id="messages" name="messages" size="5" onclick="editMessage('messages')" >
	<option value="default" selected="selected">Method:</option>
	</select><br><br>
	<input id="method" type="text" name="user" size="13">
	<input type="button" value="Delete" onclick="submitChange('delete')" ><br><br>
	B: <input id="object2" type="text" name="user" size="13"><br>
	Choose message you want to insert the new message after
	<select id="objectoptions" name="objectselect" size="1" onchange="loadMessageOptions('objectoptions')"  >
	<option value="default" selected="selected">1</option>
	</select><br><br>
	<select id="messageoptions" name="messageselect" size="1"  >
	</select><br><br>
	Method: <input id="methodinsert" type="text" name="user" size="13">
	<input type="button" value="Insert" onclick="submitChange('insert')" ><br><br>

	<input type="button" value="Done" onclick="submitChange('name')" >
	</form>
	
	
	<form class="inputform" id="editForm2" name="input"  method="post" >
	<input id="id" type="text" name="user" size="13" style="display:none" >
	<br>Name: <select id="objects" name="messages" size="1"  onchange="alert('clicked');" >
	</select><br><br>
	<select id="messages" name="messages" size="5" onclick="editMessage('messages')" >
	<option value="default" selected="selected">Method:</option>
	</select><br><br>
	<input id="method" type="text" name="user" size="13"><br><br>
	
	<input type="button" value="Done" onclick="submitChange('name')" >
	</form>
	
	</div>
	 
	<div id="buttones" >
	<!--<<input type="image" src="<?php echo base_url('/images/download5.jpg');?>" alt="Download" onclick="exportServerSide()" width="30" height="30" style="background-size: 100%">-->
	<button id="undo"   type="button" value="Undo" onclick="undo()" > 
	<img class="buttonsimage" src="<?php echo base_url('/images/undo.png');?>" ></button>
	<button  id="redo"   type="button" value="Redo" onclick="redo()" >
	<img class="buttonsimage" src="<?php echo base_url('/images/redo.png');?>" ></button>
	<button  id="save"   type="button" onclick="saveToDB()" >
	<img id="download" class="buttonsimage1" src="<?php echo base_url('/images/upload2.jpg');?>" ></button>
	<button  id="export"   type="button" onclick="exportServerSide()" >
	<img id="download" class="buttonsimage1" src="<?php echo base_url('/images/download03.png');?>" ></button>
	
	</div>
	
	<div id="userdata">
	<?php if(!$this->session->userdata('user_name')) : ?>
		<div class="signin_form">
		<h1 style="text-align:center">Login</h1>
		<?php echo form_open("user/login"); ?>
		<label for="email"></label>
		<input type="text" id="email" name="email" value="Email" onFocus="if(this.value == 'Email'){this.value=''}"  onblur="if(this.value == ''){this.value='Email'}"/>
		
		<label for="password"></label>
		<input type="password" id="pass" name="pass" value="Password" onFocus="if(this.value == 'Password'){this.value=''}"  onblur="if(this.value == ''){this.value='Password'}"/ />
		</p>
		<input type="submit" class="" value="Log in"  />
		</p>
		<?php echo form_close(); ?>
		</div><!--<div class="signin_form">-->
		
		<div class="reg_form">
		<h1 style="text-align:center">Register</h1>
		<div style="text-align:center;color:red;"> <?php echo validation_errors('<p class="error">'); ?></div>
		 <?php echo form_open("user/registration"); ?>
		  <p>
		  <label for="user_name"></label>
		  <input type="text" id="user_name" name="user_name" value="Name"  onFocus="if(this.value == 'Name'){this.value=''}"  onblur="if(this.value == ''){this.value='Name'}" />
		  </p>
		  <p>
		  <label for="email_address"></label>
		  <input type="text" id="email_address" name="email_address" value="Email Address"  onFocus="if(this.value == 'Email Address'){this.value=''}"  onblur="if(this.value == ''){this.value='Email Address'}" />
		  </p>
		  <p>
		  <label for="password"></label>
		  <input type="password" id="password" name="password" value="0000000" onFocus="if(this.value == '0000000'){this.value=''}"  onblur="if(this.value == ''){this.value='0000000'}" />
		  </p>
		  <p>
		  <label for="con_password"></label>
		  <input type="password" id="con_password" name="con_password" value="1111111" onFocus="if(this.value == '0000000'){this.value=''}"  onblur="if(this.value == ''){this.value='0000000'}" />
		  </p>
		  <p>
		  <input type="submit" class="greenButton" value="Submit" />
		  </p>
		 <?php echo form_close(); ?>
		</div><!--<div class="reg_form">-->
		</div><!--<div id="content">-->
		
	<?php else : ?>
		<div class="contenta">
		  <h2>Welcome <?php echo $this->session->userdata('user_name'); ?>!</h2>
		  <p>This section represents the area that only logged in members can access.</p>
		  <h4><?php echo anchor('user/logout', 'Logout'); ?></h4>
		  <table class="info-table" border="1">
				<tr>
					
					<th>Diagram Name</th>
					<th>Date Created</th>
					<th></th>
				</tr>
	
		<?php foreach($diagramData as $value) {	 ?>
				<tr>
					<td><a href="javascript:fetchFromDB('<?php echo $value['diagram_name'];?>',5)"><?php echo $value['diagram_name'];?></a></td>
					<td><?php echo $value['diagram_id'];?></td>
				</tr>
		<?php } ?>                    					
		
			</table>
		  
		</div><!--<div class="content">-->
	<?php endif; ?>			
	</div>
	
	<div id="diagram">
	</div>		
</body>